﻿using Fiddler;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using FiddlerExUtils.Components;
using FiddlerExUtils.Tools;
using System.Collections.Specialized;
using System.Text;
using System.IO;
using FiddlerExUtils.Helper;
using FiddlerExUtils.UserControls;
using System.Collections;
using System.Threading;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using FiddlerExScripts;
using System.Data.SQLite;
using System.Data;

namespace FiddlerInspectorsEx
{
    public class JSONView : UserControl
    {
        private Button btnCollapseAll;
        private Button btnExpandAll;
        private IContainer components;
        private Label lblStatus;
        private Panel pnlFooter;
        public Button textShowBtn;
        private TextBox txtSearch;

        public Button Btn_JSONZhuanYi;

        public static HTTPRequestHeaders headers;
        public static string reqBody;
        public static string resBody;
        public TextBox TXT_HeadLine;
        public WebBrowserComponent webBrowser1;
        public bool isShowTextBox = false;
        public bool isJson = false;
        public TreeViewComponent tvJSON;
        public RichTextBoxControl rtbox_Json;
        public Session oSession;

        /// <summary>
        /// 请求断点列表
        /// </summary>
        public ArrayList bpuURI = new ArrayList();
        /// <summary>
        /// 响应断点列表
        /// </summary>
        public ArrayList bpaURI = new ArrayList();
        /// <summary>
        /// Mock列表
        /// </summary>
        public static ArrayList mockList = new ArrayList();
        /// <summary>
        /// 模拟弱网的接口
        /// </summary>
        public static Dictionary<string, Dictionary<string, string>> simulateSpeedsDic = new Dictionary<string, Dictionary<string, string>>();
        /// <summary>
        /// Host过滤列表
        /// </summary>
        //public static ArrayList captureHostList = new ArrayList();

        private readonly MenuItem bpuMnu;
        private readonly MenuItem bpaMnu;
        private readonly MenuItem bpubpaMnu;
        private readonly MenuItem compareMnu;
        private readonly MenuItem copyBodyToFileMnu;
        private readonly MenuItem copyBodyToClipboardMnu;
        private readonly MenuItem addMockListMnu;
        private readonly MenuItem simulateSpeedsMnu;
        private readonly MenuItem captureHostMnu;

        private TreeViewControl treeViewControl;
        private MenuItem changeSessionTreeViewMnu;

        public static SqliteHelper sqllite;
        private Configuration config;


        public JSONView()
        {
            this.InitializeComponent();

            this.tvJSON.BackColor = CONFIG.colorDisabledEdit;
            Utilities.SetCueText(this.txtSearch, "Search...");
            if (CONFIG.flFontSize != this.tvJSON.Font.Size)
            {
                this.tvJSON.Font = new Font(this.tvJSON.Font.FontFamily, CONFIG.flFontSize);
            }
        }

        public JSONView(IBaseInspector2 inspector)
        {
            this.InitializeComponent();

            //TreeView视图
            treeViewControl = new TreeViewControl
            {
                Name = "treeViewControl",
                Dock = DockStyle.Fill
            };

            this.tvJSON.BackColor = CONFIG.colorDisabledEdit;
            Utilities.SetCueText(this.txtSearch, "Search...");
            if (CONFIG.flFontSize != this.tvJSON.Font.Size)
            {
                this.tvJSON.Font = new Font(this.tvJSON.Font.FontFamily, CONFIG.flFontSize);
            }

            if (inspector is IRequestInspector2)
            {
                //初始化FiddlerEx目录
                CommonFunction.CreateFiddlerExDirectory();
                //初始化数据库db
                try
                {
                    string connstr = string.Format("Data Source={0}", CommonFunction.GetFiddlerExDataDirectory() + "MockData.db");
                    sqllite = new SqliteHelper(connstr);
                }
                catch (Exception e)
                {
                    FiddlerApplication.Log.LogString("SqliteHelper@@: " + e.ToString());
                }

                bpuMnu = new MenuItem("设置请求前断点", FiddlerApplicationUI_SessionMnu_Click)
                {
                    Name = "_bpu"
                };
                bpaMnu = new MenuItem("设置响应后断点", FiddlerApplicationUI_SessionMnu_Click)
                {
                    Name = "_bpa"
                };
                bpubpaMnu = new MenuItem("清除插件所有断点", FiddlerApplicationUI_SessionMnu_Click)
                {
                    Name = "_bpubpa"
                };
                compareMnu = new MenuItem("Session对比", FiddlerApplicationUI_SessionMnu_Click)
                {
                    Name = "_compareMnu"
                };
                copyBodyToFileMnu = new MenuItem("复制为文件到剪贴板", FiddlerApplicationUI_SessionMnu_Click)
                {
                    Name = "_copyBodyToFileMnu"
                };
                copyBodyToClipboardMnu = new MenuItem("复制请求响应Body", FiddlerApplicationUI_SessionMnu_Click)
                {
                    Name = "_copyBodyToClipboardMnu"
                };
                addMockListMnu = new MenuItem("添加到Mock列表", FiddlerApplicationUI_SessionMnu_Click)
                {
                    Name = "_addMockListMnu"
                };
                simulateSpeedsMnu = new MenuItem("模拟接口弱网", FiddlerApplicationUI_SessionMnu_Click)
                {
                    Name = "_simulateSpeedsMnu"
                };
                captureHostMnu = new MenuItem("添加到Host过滤列表", FiddlerApplicationUI_SessionMnu_Click)
                {
                    Name = "_captureHostMnu"
                };

                FiddlerApplication.UI.mnuSessionContext.MenuItems.Add(0, bpuMnu);
                FiddlerApplication.UI.mnuSessionContext.MenuItems.Add(1, bpaMnu);
                FiddlerApplication.UI.mnuSessionContext.MenuItems.Add(2, bpubpaMnu);
                FiddlerApplication.UI.mnuSessionContext.MenuItems.Add(3, compareMnu);
                FiddlerApplication.UI.mnuSessionContext.MenuItems.Add(4, copyBodyToFileMnu);
                FiddlerApplication.UI.mnuSessionContext.MenuItems.Add(5, copyBodyToClipboardMnu);
                FiddlerApplication.UI.mnuSessionContext.MenuItems.Add(6, addMockListMnu);
                FiddlerApplication.UI.mnuSessionContext.MenuItems.Add(7, simulateSpeedsMnu);
                FiddlerApplication.UI.mnuSessionContext.MenuItems.Add(8, captureHostMnu);
                FiddlerApplication.UI.mnuSessionContext.Popup += FiddlerApplicationUI_MnuSessionContext_Popup;

                FiddlerApplication.UI.Shown += UI_Load;
                FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest;
                FiddlerApplication.BeforeResponse += FiddlerApplication_BeforeResponse;
                FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete;
                //Inspectors分割线自适应
                FiddlerApplication.UI.pageInspector.SizeChanged += FiddlerApplicationUI_Inspectors_SizeChanged;
                //Fiddler关闭监听
                FiddlerApplication.UI.FormClosing += FiddlerApplicationUI_FormClosing;

                FiddlerApplication.Prefs.SetStringPref("fiddler.ui.inspectors.request.alwaysuse", "requestview");
                FiddlerApplication.Prefs.SetStringPref("fiddler.ui.inspectors.response.alwaysuse", "responseview");

                if (!FiddlerApplication.Prefs.ToString().Contains("fiddlerex.func.timeout"))
                {
                    FiddlerApplication.Prefs.SetInt32Pref("fiddlerex.func.timeout", 1000);
                }

                if (!FiddlerApplication.Prefs.ToString().Contains("fiddlerex.urlconfig.updatecheckurl"))
                {
                    FiddlerApplication.Prefs.SetStringPref("fiddlerex.urlconfig.updatecheckurl", "https://gitee.com/591028872/fiddler-inspectors-ex/raw/master/FiddlerInspectorsEx/config.json");
                }

                if (!FiddlerApplication.Prefs.ToString().Contains("fiddlerex.urlconfig.updatecheckdate"))
                {
                    FiddlerApplication.Prefs.SetStringPref("fiddlerex.urlconfig.updatecheckdate", "2022-12-15");
                }

                if (!FiddlerApplication.Prefs.ToString().Contains("fiddlerex.webbrowser.json.isdefaultexpand"))
                {
                    FiddlerApplication.Prefs.SetBoolPref("fiddlerex.webbrowser.json.isdefaultexpand", true);
                }

                if (!FiddlerApplication.Prefs.ToString().Contains("fiddlerex.func.isdiffheaders"))
                {
                    FiddlerApplication.Prefs.SetBoolPref("fiddlerex.func.isdiffheaders", true);
                }

                try
                {
                    //插件配置初始化
                    config = new Configuration();
                    config.LoadConfig();
                    config.FiddlerLogClear();
                    config.FiddlerSettingsCheck();
                    config.FiddlerUpdateCheck(false);
                }
                catch (Exception e)
                {
                    FiddlerApplication.Log.LogString("JSONView: " + e.Message);
                }
            }
        }

        private void UI_Load(object sender, EventArgs e)
        {
            MenuItem mockFiddlerMnu = new MenuItem("&Mock", FiddlerApplicationUI_Mock_Click);
            FiddlerApplication.UI.mnuMain.MenuItems.Add(mockFiddlerMnu);
            MenuItem downloadFiddlerMnu = new MenuItem("下载", FiddlerApplicationUI_DownloadFiddlerMnu_Click);
            FiddlerApplication.UI.mnuMain.MenuItems.Add(downloadFiddlerMnu);

            FiddlerApplication.UI.Controls[2].Controls.Add(treeViewControl);
            changeSessionTreeViewMnu = new MenuItem("Tree Session List", FiddlerApplicationUI_ChangeSessionTreeViewMnu_Click, Shortcut.F2)
            {
                Name = "changeSessionTreeView"
            };
            FiddlerApplication.UI.mnuMain.MenuItems[4].MenuItems.Add(changeSessionTreeViewMnu);

            treeViewControl.SessionStart();

            if (!FiddlerApplication.Prefs.ToString().Contains("fiddlerex.session.hostfilter")) { FiddlerApplication.Prefs.SetStringPref("fiddlerex.session.hostfilter", ""); }
            if (!FiddlerApplication.Prefs.ToString().Contains("fiddlerex.session.sessioncolor")) { FiddlerApplication.Prefs.SetStringPref("fiddlerex.session.sessioncolor", "Orange"); }
            if (!FiddlerApplication.Prefs.ToString().Contains("fiddlerex.session.mockcolor")) { FiddlerApplication.Prefs.SetStringPref("fiddlerex.session.mockcolor", "Blue"); }
        }

        private ArrayList GetCaptureHostList()
        {
            ArrayList captureHostList = new ArrayList();
            //hostfilter初始化
            string hostFilter = FiddlerApplication.Prefs.GetStringPref("fiddlerex.session.hostfilter", "").Trim();
            foreach (string h in hostFilter.Split(';'))
            {
                if (h.Trim() != "" && !captureHostList.Contains(h.Trim()))
                    captureHostList.Add(h.Trim());
            }
            return captureHostList;
        }

        private void ClearCaptureHostList()
        {
            FiddlerApplication.Prefs.SetStringPref("fiddlerex.session.hostfilter", "");
        }

        private void AddToCaptureHostList(string hostname)
        {
            bool isCaptureHost = IsCaptureHost(hostname);
            if (!isCaptureHost)
            {
                ArrayList new_hosts = new ArrayList();
                new_hosts = GetCaptureHostList();
                new_hosts.Add(hostname);

                string hostFilters = "";
                foreach (string host in new_hosts)
                {
                    if (hostFilters == "")
                    {
                        hostFilters += host.Trim();
                    }
                    else
                    {
                        hostFilters += ";" + host.Trim();
                    }
                }

                FiddlerApplication.Prefs.SetStringPref("fiddlerex.session.hostfilter", hostFilters);
            }
        }

        private void RemoveFromCaptureHostList(string hostname)
        {
            ArrayList newHosts = new ArrayList();
            foreach (string host in GetCaptureHostList())
            {
                if (!hostname.Contains(host.Trim()))
                {
                    newHosts.Add(host.Trim());
                }
            }

            ClearCaptureHostList();
            foreach (string host in newHosts)
            {
                AddToCaptureHostList(host);
            }
        }

        private bool IsCaptureHost(string hostname)
        {
            bool isCapturedHost = false;
            foreach (string host in GetCaptureHostList())
            {
                if (hostname.Contains(host.Trim()))
                {
                    isCapturedHost = true;
                    break;
                }
            }
            return isCapturedHost;
        }

        private void FiddlerApplicationUI_Inspectors_SizeChanged(object sender, EventArgs e)
        {
            if (changeSessionTreeViewMnu != null && changeSessionTreeViewMnu.Checked == true) //Tree Session list view
            {
                Splitter splitter = (Splitter)FiddlerApplication.UI.pageInspector.Controls["splitterInspector"];
                splitter.SplitPosition = FiddlerApplication.UI.pageInspector.Width / 2;
            }
            else //normal view
            {
                Splitter splitter = (Splitter)FiddlerApplication.UI.pageInspector.Controls["splitterInspector"];
                splitter.SplitPosition = FiddlerApplication.UI.pageInspector.Height / 2;
            }
        }

        private void FiddlerApplicationUI_ChangeSessionTreeViewMnu_Click(object sender, EventArgs e)
        {
            if (((MenuItem)sender).Checked == false) //Tree Session list view
            {
                changeSessionTreeViewMnu.Checked = true;
                FiddlerApplication.UI.lvSessions.Visible = false;
                FiddlerApplication.UI.Controls["pnlSessions"].Controls["treeViewControl"].Visible = true;
                //inspector左右视图
                FiddlerApplication.UI.pageInspector.Controls["splitterInspector"].Dock = DockStyle.Left;
                FiddlerApplication.UI.pageInspector.Controls["tabsRequest"].Dock = DockStyle.Left;
                Splitter splitter = (Splitter)FiddlerApplication.UI.pageInspector.Controls["splitterInspector"];
                splitter.SplitPosition = FiddlerApplication.UI.pageInspector.Width / 2;
                FiddlerApplication.UI.Update();
            }
            else //normal view
            {
                changeSessionTreeViewMnu.Checked = false;
                FiddlerApplication.UI.lvSessions.Visible = true;
                FiddlerApplication.UI.Controls["pnlSessions"].Controls["treeViewControl"].Visible = false;
                //inspector上下视图
                FiddlerApplication.UI.pageInspector.Controls["splitterInspector"].Dock = DockStyle.Top;
                FiddlerApplication.UI.pageInspector.Controls["tabsRequest"].Dock = DockStyle.Top;
                Splitter splitter = (Splitter)FiddlerApplication.UI.pageInspector.Controls["splitterInspector"];
                splitter.SplitPosition = FiddlerApplication.UI.pageInspector.Height / 2;
                FiddlerApplication.UI.Update();
            }
        }

        private void FiddlerApplicationUI_DownloadFiddlerMnu_Click(object sender, EventArgs e)
        {
            Utilities.LaunchHyperlink("https://www.telerik.com/download/fiddler/fiddler4");
        }

        private void FiddlerApplicationUI_Mock_Click(object sender, EventArgs e)
        {
            config.FiddlerUpdateCheck(false);

            if (CheckChildFrmExist("Mock") != null)
            {
                return;
            }
            else
            {
                MockFrm mockFrm = new MockFrm();
                mockFrm.Name = "Mock";
                mockFrm.Show();
            }
        }

        /// <summary>
        /// 检测窗口是否已打开
        /// </summary>
        /// <param name="childFrmName">参数窗体名称</param>
        /// <param name="index"></param>
        /// <returns></returns>
        private MockFrm CheckChildFrmExist(string childFrmName)
        {
            foreach (Form childFrm in Application.OpenForms)
            {
                if (childFrm.Name == childFrmName)
                {
                    if (childFrm.WindowState == FormWindowState.Minimized)
                        childFrm.WindowState = FormWindowState.Normal;
                    childFrm.Activate();
                    return childFrm as MockFrm;
                }
            }
            return null;
        }

        private void FiddlerApplication_AfterSessionComplete(Session oSession)
        {
            treeViewControl.EnqueueSession(oSession);
        }

        private void FiddlerApplication_BeforeResponse(Session oSession)
        {
            treeViewControl.EnqueueSession(oSession);
            oSession.utilDecodeResponse(true);
            SQLiteDataReader reader = sqllite.ReadTable("mock", SqliteHelper.columnName, new string[] { "Enable", "\"" + oSession.fullUrl.ToLower() + "\"" }, new string[] { "=", "like" }, new string[] { "1", "\"%\" || URL || \"%\"" });
            if (reader.HasRows)
            {
                DataTable table = new DataTable();
                table.Load(reader);

                //请求Body自动替换
                for (int i = 0; i < table.Rows.Count; i++) //遍历行
                {
                    string id = table.Rows[i][0].ToString();
                    string enable = table.Rows[i][1].ToString();
                    string url = table.Rows[i][2].ToString();
                    //string oldReq = table.Rows[i][3].ToString();
                    //string newReq = table.Rows[i][4].ToString();
                    string oldRes = table.Rows[i][5].ToString();
                    string newRes = table.Rows[i][6].ToString();
                    string responseCode = table.Rows[i][7].ToString();
                    string mockType = table.Rows[i][8].ToString();

                    //string req = oSession.GetRequestBodyAsString();
                    oSession.responseCode = Convert.ToInt16(responseCode);
                    FiddlerApplication.Log.LogString("Session ID：" + oSession.id + "，ResponseCode已替换为：" + responseCode);
                    if (newRes != "")
                    {
                        string res = CommonFunction.ConvertJsonString(oSession.GetResponseBodyAsString());
                        if (oldRes.Trim() == "")
                        {
                            res = newRes;
                            ResponseReplace(oSession, res);
                            oSession["response-replace"] = string.Format(" 注意响应Body已全部替换(ID={0})", id);
                        }
                        else
                        {
                            string[] oldReplaceList = oldRes.Split(new string[] { "\n" }, StringSplitOptions.None);
                            string[] newReplaceList = newRes.Split(new string[] { "\n" }, StringSplitOptions.None);
                            for (int j = 0; j < oldReplaceList.Length; j++)
                            {
                                if (res.Contains(oldReplaceList[j]))
                                {
                                    string newStr = j >= newReplaceList.Length ? "" : newReplaceList[j];
                                    res = res.Replace(oldReplaceList[j], newStr);
                                    ResponseReplace(oSession, res);
                                    oSession["response-replace"] += string.Format(" 注意响应Body已部分替换(ID={0})：{1} → {2}", id, oldReplaceList[j], newStr);
                                }
                            }
                        }
                        //MockFrm mockFrm = CheckChildFrmExist("Mock");
                        //if (mockFrm != null)
                        //{
                        //    mockFrm.DataGridView_BodyReplace.Rows[i].DefaultCellStyle.BackColor = Color.Orange;
                        //    Thread.Sleep(200);
                        //    mockFrm.DataGridView_BodyReplace.Rows[i].DefaultCellStyle.BackColor = SystemColors.Window;
                        //}
                        break;
                    }
                }
            }


            if (changeSessionTreeViewMnu != null && changeSessionTreeViewMnu.Checked)
            {
                string serviceName = oSession.fullUrl;

                //TreeViewSession设置响应断点
                if (TreeViewControl.bpaURI.Count > 0)
                {
                    if (TreeViewControl.bpaURI.Contains(serviceName))
                    {
                        oSession.oFlags["x-breakresponse"] = "uri";
                    }
                    else
                    {
                        foreach (string uri in TreeViewControl.bpaURI)
                        {
                            if (oSession.fullUrl.Contains(uri))
                            {
                                oSession.oFlags["x-breakresponse"] = "uri";
                                break;
                            }
                        }
                    }
                }
            }
            else
            {
                //设置响应断点
                if (this.bpaURI.Count > 0 && this.bpaURI.Contains(oSession.fullUrl))
                {
                    oSession.oFlags["x-breakresponse"] = "uri";
                }
            }

            //Session Color
            if (oSession.responseCode == 200 && !oSession.RequestMethod.Equals("CONNECT"))
            {
                foreach (string host in GetCaptureHostList())
                {
                    if (oSession.hostname.Contains(host.Trim()))
                    {
                        oSession["ui-color"] = FiddlerApplication.Prefs.GetStringPref("fiddlerex.session.sessioncolor", "Black");
                        break;
                    }
                }
            }
            //Mock Color
            if (oSession.oFlags.ContainsKey("request-replace") || oSession.oFlags.ContainsKey("response-replace"))
            {
                oSession["ui-color"] = FiddlerApplication.Prefs.GetStringPref("fiddlerex.session.mockcolor", "Blue");
            }
        }

        private void FiddlerApplication_BeforeRequest(Session oSession)
        {
            bool isCaptureHost = false;
            foreach (string host in GetCaptureHostList())
            {
                if (oSession.hostname.Contains(host.Trim()))
                {
                    isCaptureHost = true;
                    break;
                }
            }

            if (GetCaptureHostList().Count > 0 && !isCaptureHost)
            {
                oSession.Ignore();
                FiddlerApplication.Log.LogString("Host过滤，已忽略：" + oSession.fullUrl);
                return;
            }

            treeViewControl.EnqueueSession(oSession);

            oSession.utilDecodeRequest(true);
            //Sqlite查询字段被包含：http://ask.sov5.cn/q/0EiH4VFWTK
            SQLiteDataReader reader = sqllite.ReadTable("mock", SqliteHelper.columnName, new string[] { "Enable", "\"" + oSession.fullUrl.ToLower() + "\"" }, new string[] { "=", "like" }, new string[] { "1", "\"%\" || URL || \"%\"" });
            if (reader.HasRows)
            {
                DataTable table = new DataTable();
                table.Load(reader);

                //请求Body自动替换
                for (int i = 0; i < table.Rows.Count; i++) //遍历行
                {
                    string id = table.Rows[i][0].ToString();
                    string enable = table.Rows[i][1].ToString();
                    string url = table.Rows[i][2].ToString();
                    string oldReq = table.Rows[i][3].ToString();
                    string newReq = table.Rows[i][4].ToString();
                    string oldRes = table.Rows[i][5].ToString();
                    string newRes = table.Rows[i][6].ToString();
                    //string responseCode = table.Rows[i][7].ToString();
                    string mockType = table.Rows[i][8].ToString();

                    string req = CommonFunction.ConvertJsonString(oSession.GetRequestBodyAsString());

                    if (newRes != "")
                    {
                        //是否ByPassServer
                        if (oldRes.Trim() == "" && !oSession.isFlagSet(SessionFlags.ResponseGeneratedByFiddler))
                        {
                            oSession.utilCreateResponseAndBypassServer();
                        }
                    }
                    if (newReq != "")
                    {
                        if (oldReq.Trim() == "")
                        {
                            req = newReq;
                            RequestReplace(oSession, req);
                            oSession["request-replace"] = string.Format(" 注意请求Body已全部替换(ID={0})", id);
                        }
                        else
                        {
                            string[] oldReplaceList = oldReq.Split(new string[] { "\n" }, StringSplitOptions.None);
                            string[] newReplaceList = newReq.Split(new string[] { "\n" }, StringSplitOptions.None);
                            for (int j = 0; j < oldReplaceList.Length; j++)
                            {
                                if (req.Contains(oldReplaceList[j]))
                                {
                                    string newStr = j >= newReplaceList.Length ? "" : newReplaceList[j];
                                    req = req.Replace(oldReplaceList[j], newStr);
                                    RequestReplace(oSession, req);
                                    oSession["request-replace"] += string.Format(" 注意请求Body已部分替换(ID={0})：{1} → {2}", id, oldReplaceList[j], newStr);
                                }
                            }
                        }
                        //MockFrm mockFrm = CheckChildFrmExist("Mock");
                        //if (mockFrm != null)
                        //{
                        //    mockFrm.DataGridView_BodyReplace.Rows[i].DefaultCellStyle.BackColor = Color.Orange;
                        //    Thread.Sleep(200);
                        //    mockFrm.DataGridView_BodyReplace.Rows[i].DefaultCellStyle.BackColor = SystemColors.Window;
                        //}
                        break;
                    }
                }
            }
            //单接口模拟弱网
            int index = oSession.fullUrl.IndexOf('?');
            string subUrl = oSession.fullUrl.Substring(0, index > 0 ? index : oSession.fullUrl.Length);
            if (simulateSpeedsDic.ContainsKey(subUrl))
            {
                Dictionary<string, string> speeds = simulateSpeedsDic[subUrl];

                // Delay sends by ms per KB uploaded.
                oSession["request-trickle-delay"] = speeds["up"];
                // Delay receives by ms per KB downloaded.
                oSession["response-trickle-delay"] = speeds["down"];
                FiddlerApplication.Log.LogString(string.Format("Session ID：{0} 接口弱网：Up：{1}ms/KB Down：{2}ms/KB", oSession.id, speeds["up"], speeds["down"]));
            }

            if (changeSessionTreeViewMnu != null && changeSessionTreeViewMnu.Checked)
            {
                string serviceName = oSession.fullUrl;

                //TreeViewSession设置请求断点
                if (TreeViewControl.bpuURI.Count > 0)
                {
                    if (TreeViewControl.bpuURI.Contains(serviceName))
                    {
                        oSession.oFlags["x-breakrequest"] = "uri";
                    }
                    else
                    {
                        foreach (string uri in TreeViewControl.bpuURI)
                        {
                            if (oSession.fullUrl.Contains(uri))
                            {
                                oSession.oFlags["x-breakrequest"] = "uri";
                                break;
                            }
                        }
                    }
                }
            }
            else
            {
                //设置请求断点
                if (this.bpuURI.Count > 0 && this.bpuURI.Contains(oSession.fullUrl))
                {
                    oSession.oFlags["x-breakrequest"] = "uri";
                }
            }

        }

        /// <summary>
        /// 自动替换-修改请求body及reqdata
        /// </summary>
        /// <param name="oSession">需要处理的session</param>
        /// <param name="req">解密的请求body</param>
        private void RequestReplace(Session oSession, string req)
        {
            oSession.utilSetRequestBody(req);
        }

        /// <summary>
        /// 自动替换-修改响应body及reqdata
        /// </summary>
        /// <param name="oSession">需要处理的session</param>
        /// <param name="res">解密的响应body</param>
        private void ResponseReplace(Session oSession, string res)
        {
            oSession.utilSetResponseBody(res);
        }

        private void FiddlerApplicationUI_FormClosing(object sender, FormClosingEventArgs e)
        {
            sqllite.CloseConnection();
            System.Diagnostics.Process[] app = System.Diagnostics.Process.GetProcessesByName("WinMergeU");
            if (app.Length > 0) app[0].Kill();
        }

        private void FiddlerApplicationUI_MnuSessionContext_Popup(object sender, EventArgs e)
        {
            //new Thread(NetworkSimulator) { IsBackground = true }.Start();
            //NetworkSimulator();
            #region 设置请求、响应断点-菜单项
            if (FiddlerApplication.UI.GetSelectedSessions().Length == 1)
            {
                FiddlerApplication.UI.mnuSessionContext.MenuItems["_bpu"].Enabled = true;
                FiddlerApplication.UI.mnuSessionContext.MenuItems["_bpa"].Enabled = true;
                Session firstSession = FiddlerApplication.UI.GetSelectedSessions()[0];
                string serName = firstSession.fullUrl;

                if (this.bpuURI.Contains(serName))
                {
                    FiddlerApplication.UI.mnuSessionContext.MenuItems["_bpu"].Checked = true;
                }
                else
                {
                    FiddlerApplication.UI.mnuSessionContext.MenuItems["_bpu"].Checked = false;
                }
                if (this.bpaURI.Contains(serName))
                {
                    FiddlerApplication.UI.mnuSessionContext.MenuItems["_bpa"].Checked = true;
                }
                else
                {
                    FiddlerApplication.UI.mnuSessionContext.MenuItems["_bpa"].Checked = false;
                }
            }
            else
            {
                FiddlerApplication.UI.mnuSessionContext.MenuItems["_bpu"].Enabled = false;
                FiddlerApplication.UI.mnuSessionContext.MenuItems["_bpa"].Enabled = false;
            }
            #endregion
            #region 对比Session-菜单项
            if (FiddlerApplication.UI.GetSelectedSessions().Length == 2)
            {
                FiddlerApplication.UI.mnuSessionContext.MenuItems["_compareMnu"].Enabled = true;
            }
            else
            {
                FiddlerApplication.UI.mnuSessionContext.MenuItems["_compareMnu"].Enabled = false;
            }
            #endregion
            #region 复制为文件到剪贴板-菜单项
            if (FiddlerApplication.UI.GetSelectedSessions().Length > 0)
            {
                FiddlerApplication.UI.mnuSessionContext.MenuItems["_copyBodyToFileMnu"].Enabled = true;
            }
            else
            {
                FiddlerApplication.UI.mnuSessionContext.MenuItems["_copyBodyToFileMnu"].Enabled = false;
            }
            #endregion
            #region 复制请求响应Body-菜单项
            if (FiddlerApplication.UI.GetSelectedSessions().Length == 1)
            {
                FiddlerApplication.UI.mnuSessionContext.MenuItems["_copyBodyToClipboardMnu"].Enabled = true;
            }
            else
            {
                FiddlerApplication.UI.mnuSessionContext.MenuItems["_copyBodyToClipboardMnu"].Enabled = false;
            }
            #endregion
            #region 添加到本地Mock列表-菜单项
            if (FiddlerApplication.UI.GetSelectedSessions().Length > 0)
            {
                FiddlerApplication.UI.mnuSessionContext.MenuItems["_addMockListMnu"].Enabled = true;
            }
            else
            {
                FiddlerApplication.UI.mnuSessionContext.MenuItems["_addMockListMnu"].Enabled = false;
            }
            #endregion
            #region 模拟接口弱网-菜单项
            if (FiddlerApplication.UI.GetSelectedSessions().Length == 1)
            {
                Session firstSession = FiddlerApplication.UI.GetSelectedSessions()[0];
                FiddlerApplication.UI.mnuSessionContext.MenuItems["_simulateSpeedsMnu"].Enabled = true;
                int index = firstSession.fullUrl.IndexOf('?');
                string subUrl = firstSession.fullUrl.Substring(0, index > 0 ? index : firstSession.fullUrl.Length);
                if (simulateSpeedsDic.ContainsKey(subUrl))
                {
                    FiddlerApplication.UI.mnuSessionContext.MenuItems["_simulateSpeedsMnu"].Checked = true;
                }
                else
                {
                    FiddlerApplication.UI.mnuSessionContext.MenuItems["_simulateSpeedsMnu"].Checked = false;
                }
            }
            else
            {
                FiddlerApplication.UI.mnuSessionContext.MenuItems["_simulateSpeedsMnu"].Enabled = false;
                FiddlerApplication.UI.mnuSessionContext.MenuItems["_simulateSpeedsMnu"].Checked = false;
            }
            #endregion
            #region 添加到过滤Host列表-菜单项
            if (FiddlerApplication.UI.GetSelectedSessions().Length == 1)
            {
                captureHostMnu.Text = "添加到Host过滤列表";
                captureHostMnu.Enabled = true;

                bool isCapturedHost = IsCaptureHost(FiddlerApplication.UI.GetSelectedSessions()[0].hostname);
                if (isCapturedHost)
                {
                    captureHostMnu.Checked = true;
                }
                else
                {
                    captureHostMnu.Checked = false;
                }
            }
            else
            {
                captureHostMnu.Checked = false;
                captureHostMnu.Text = "清空Host过滤列表";
            }
            #endregion
        }

        private void FiddlerApplicationUI_SessionMnu_Click(object sender, EventArgs e)
        {
            if (FiddlerApplication.UI.GetSelectedSessions().Length > 0)
            {
                Session firstSession = FiddlerApplication.UI.GetSelectedSessions()[0];
                string serName = firstSession.fullUrl;
                //设置请求断点
                if (((MenuItem)sender).Name == "_bpu")
                {
                    if (this.bpuURI.Contains(serName))
                    {
                        this.bpuURI.Remove(serName);
                        firstSession.ThreadResume(); //唤醒断点
                    }
                    else
                    {
                        this.bpuURI.Add(serName);
                    }
                }
                //设置响应断点
                else if (((MenuItem)sender).Name == "_bpa")
                {
                    if (this.bpaURI.Contains(serName))
                    {
                        this.bpaURI.Remove(serName);
                        firstSession.ThreadResume(); //唤醒断点
                    }
                    else
                    {
                        this.bpaURI.Add(serName);
                    }
                }
                //Session对比
                else if (((MenuItem)sender).Name == "_compareMnu")
                {
                    CommonFunction.CompareSession(firstSession, FiddlerApplication.UI.GetSelectedSessions()[1]);
                }
                //复制为文件到剪贴板
                else if (((MenuItem)sender).Name == "_copyBodyToFileMnu")
                {
                    StringCollection stringCollection = new StringCollection();
                    foreach (Session oSession in FiddlerApplication.UI.GetSelectedSessions())
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.AppendLine("请求时间:");
                        sb.AppendLine(oSession.Timers.ClientBeginRequest.TimeOfDay.ToString());
                        sb.AppendLine();
                        sb.AppendLine("RequestURL:");
                        sb.AppendLine(oSession.fullUrl);
                        sb.AppendLine();
                        sb.AppendLine("请求Body:");
                        sb.AppendLine(oSession.GetRequestBodyAsString());
                        sb.AppendLine();
                        sb.AppendLine("响应Body:");
                        sb.AppendLine(oSession.GetResponseBodyAsString());
                        sb.AppendLine();

                        string fileName = CommonFunction.GetFiddlerExExportDirectory() + string.Format("FiddlerEx_{0}_{1}.txt", oSession.id, DateTime.Now.ToString("yyyyMMddHHmmssfff"));
                        try
                        {
                            // 创建文件，准备写入
                            FileStream fs = File.Open(fileName,
                                    FileMode.Create,
                                    FileAccess.Write);
                            StreamWriter wr = new StreamWriter(fs);
                            wr.WriteLine(sb);

                            // 关闭文件
                            wr.Flush();
                            wr.Close();
                            fs.Close();

                            stringCollection.Add(fileName); //添加到文件数组
                        }
                        catch (Exception ex)
                        {
                            FiddlerApplication.Log.LogString(ex.StackTrace);
                        }
                    }

                    if (stringCollection.Count > 0)
                    {
                        DataObject dataObject = new DataObject();
                        dataObject.SetFileDropList(stringCollection);
                        Utilities.CopyToClipboard(dataObject);
                        FiddlerApplication.UI.SetStatusText(stringCollection.Count + "个文件已复制到剪贴板！");
                    }
                }
                //复制请求URL、请求Body、响应Body到剪贴板
                else if (((MenuItem)sender).Name == "_copyBodyToClipboardMnu")
                {
                    Utilities.CopyToClipboard(string.Format("{0}\n\r\n{1}\n\r\n{2}", firstSession.fullUrl, firstSession.GetRequestBodyAsString(), firstSession.GetResponseBodyAsString()));
                    FiddlerApplication.UI.SetStatusText("请求响应Body已复制到剪贴板！");
                }
                //添加到Mock列表
                else if (((MenuItem)sender).Name == "_addMockListMnu")
                {
                    foreach (Session os in FiddlerApplication.UI.GetSelectedSessions())
                    {
                        string url = os.fullUrl.Contains("?") ? os.fullUrl.Split('?')[0] : os.fullUrl;
                        string responseCode = os.responseCode.ToString();
                        string oldReq = "";
                        string newReq = "";
                        string oldRes = "";
                        string newRes = CommonFunction.ConvertJsonString(os.GetResponseBodyAsString(), false);

                        sqllite.InsertValues("mock", new string[] { "1", url, oldReq, newReq, oldRes, newRes, responseCode, "" });
                    }
                    MockFrm mockFrm = CheckChildFrmExist("Mock");
                    if (mockFrm != null)
                    {
                        mockFrm.RefreshMockList();
                    }
                    FiddlerApplication.UI.SetStatusText("添加到本地Mock列表成功！");
                }
                //模拟接口弱网
                else if (((MenuItem)sender).Name == "_simulateSpeedsMnu")
                {
                    List<String> urlList = new List<string>();
                    int index = firstSession.fullUrl.IndexOf('?');
                    string subUrl = firstSession.fullUrl.Substring(0, index > 0 ? index : firstSession.fullUrl.Length);
                    if (((MenuItem)sender).Checked)
                    {
                        if (simulateSpeedsDic.ContainsKey(subUrl))
                        {
                            simulateSpeedsDic.Remove(subUrl);
                            FiddlerApplication.Log.LogString("已移除接口弱网：" + subUrl);
                        }
                    }
                    else
                    {
                        urlList.Add(subUrl);
                        SimulateSpeedsFrm simulateSpeedsFrm = new SimulateSpeedsFrm(firstSession.id, urlList);
                        simulateSpeedsFrm.ShowDialog();
                    }
                }
                //Host过滤
                else if (((MenuItem)sender).Name == "_captureHostMnu")
                {
                    if (!captureHostMnu.Checked)
                    {
                        if (captureHostMnu.Text == "清空Host过滤列表")
                        {
                            ClearCaptureHostList();
                            captureHostMnu.Text = "添加到Host过滤列表";
                            FiddlerApplication.Prefs.SetStringPref("fiddlerex.session.hostfilter", "");
                            return;
                        }
                        AddToCaptureHostList(FiddlerApplication.UI.GetSelectedSessions()[0].hostname);
                    }
                    else
                    {
                        RemoveFromCaptureHostList(FiddlerApplication.UI.GetSelectedSessions()[0].hostname);
                    }
                }
            }
            if (((MenuItem)sender).Name == "_bpubpa")
            {
                this.bpuURI.Clear();
                this.bpaURI.Clear();

                FiddlerApplication.UI.actResumeAllSessions();  //唤醒断点
                FiddlerApplication.UI.SetStatusText("插件所有断点功能已清除");
            }
            if (((MenuItem)sender).Name == "_captureHostMnu")
            {
                if (captureHostMnu.Text == "清空Host过滤列表")
                {
                    ClearCaptureHostList();
                    captureHostMnu.Text = "添加到Host过滤列表";
                    FiddlerApplication.Prefs.SetStringPref("fiddlerex.session.hostfilter", "");
                    FiddlerApplication.UI.SetStatusText("插件Host过滤列表已清空！");
                    return;
                }

            }
        }

        public void BeginUpdate()
        {
            this.tvJSON.BeginUpdate();
            this.tvJSON.SuspendLayout();
        }

        private void BtnCollapseAll_Click(object sender, EventArgs e)
        {
            this.textShowBtn.Enabled = true;
            this.Btn_JSONZhuanYi.Enabled = this.rtbox_Json.GetReadOnly();
            this.rtbox_Json.Visible = false;
            this.webBrowser1.Visible = false;
            this.tvJSON.Visible = true;
            this.BeginUpdate();
            this.tvJSON.CollapseAll();
            if (this.tvJSON.Nodes.Count > 0)
            {
                this.tvJSON.Nodes[0].Expand();
                for (int i = 0; i < this.tvJSON.Nodes[0].Nodes.Count; i++)
                {
                    this.tvJSON.Nodes[0].Nodes[i].Expand();
                }
                if (this.tvJSON.SelectedNode != null)
                {
                    this.tvJSON.SelectedNode.EnsureVisible();
                }
                else
                {
                    this.tvJSON.Nodes[0].EnsureVisible();
                }
            }
            this.EndUpdate();
        }

        private void BtnExpandAll_Click(object sender, EventArgs e)
        {
            this.textShowBtn.Enabled = true;
            this.Btn_JSONZhuanYi.Enabled = this.rtbox_Json.GetReadOnly();
            this.rtbox_Json.Visible = false;
            this.webBrowser1.Visible = false;
            this.tvJSON.Visible = true;
            this.BeginUpdate();
            this.tvJSON.ExpandAll();
            if (this.tvJSON.SelectedNode != null)
            {
                this.tvJSON.SelectedNode.EnsureVisible();
            }
            else if (this.tvJSON.Nodes.Count > 0)
            {
                this.tvJSON.Nodes[0].EnsureVisible();
            }
            this.EndUpdate();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (this.components != null))
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }

        public void EndUpdate()
        {
            this.tvJSON.EndUpdate();
            this.tvJSON.ResumeLayout();
        }

        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.pnlFooter = new System.Windows.Forms.Panel();
            this.Btn_JSONZhuanYi = new System.Windows.Forms.Button();
            this.textShowBtn = new System.Windows.Forms.Button();
            this.lblStatus = new System.Windows.Forms.Label();
            this.txtSearch = new System.Windows.Forms.TextBox();
            this.btnCollapseAll = new System.Windows.Forms.Button();
            this.btnExpandAll = new System.Windows.Forms.Button();
            this.TXT_HeadLine = new System.Windows.Forms.TextBox();
            this.webBrowser1 = new FiddlerExUtils.Components.WebBrowserComponent(this.components);
            this.tvJSON = new FiddlerExUtils.Components.TreeViewComponent(this.components);
            this.rtbox_Json = new FiddlerExUtils.UserControls.RichTextBoxControl();
            this.pnlFooter.SuspendLayout();
            this.SuspendLayout();
            // 
            // pnlFooter
            // 
            this.pnlFooter.Controls.Add(this.Btn_JSONZhuanYi);
            this.pnlFooter.Controls.Add(this.textShowBtn);
            this.pnlFooter.Controls.Add(this.lblStatus);
            this.pnlFooter.Controls.Add(this.txtSearch);
            this.pnlFooter.Controls.Add(this.btnCollapseAll);
            this.pnlFooter.Controls.Add(this.btnExpandAll);
            this.pnlFooter.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.pnlFooter.Location = new System.Drawing.Point(0, 272);
            this.pnlFooter.Name = "pnlFooter";
            this.pnlFooter.Size = new System.Drawing.Size(489, 25);
            this.pnlFooter.TabIndex = 1;
            // 
            // Btn_JSONZhuanYi
            // 
            this.Btn_JSONZhuanYi.Location = new System.Drawing.Point(243, 2);
            this.Btn_JSONZhuanYi.Name = "Btn_JSONZhuanYi";
            this.Btn_JSONZhuanYi.Size = new System.Drawing.Size(75, 23);
            this.Btn_JSONZhuanYi.TabIndex = 4;
            this.Btn_JSONZhuanYi.Text = "JSON转义";
            this.Btn_JSONZhuanYi.UseVisualStyleBackColor = true;
            this.Btn_JSONZhuanYi.Click += new System.EventHandler(this.Btn_JSONZhuanYi_Click);
            // 
            // textShowBtn
            // 
            this.textShowBtn.Enabled = false;
            this.textShowBtn.Location = new System.Drawing.Point(162, 2);
            this.textShowBtn.Name = "textShowBtn";
            this.textShowBtn.Size = new System.Drawing.Size(75, 23);
            this.textShowBtn.TabIndex = 2;
            this.textShowBtn.Text = "文本模式";
            this.textShowBtn.UseVisualStyleBackColor = true;
            this.textShowBtn.Click += new System.EventHandler(this.Button1_Click);
            // 
            // lblStatus
            // 
            this.lblStatus.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.lblStatus.Location = new System.Drawing.Point(324, 3);
            this.lblStatus.Name = "lblStatus";
            this.lblStatus.Size = new System.Drawing.Size(162, 20);
            this.lblStatus.TabIndex = 3;
            this.lblStatus.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // txtSearch
            // 
            this.txtSearch.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.txtSearch.Location = new System.Drawing.Point(421, 2);
            this.txtSearch.Name = "txtSearch";
            this.txtSearch.Size = new System.Drawing.Size(65, 21);
            this.txtSearch.TabIndex = 2;
            this.txtSearch.Visible = false;
            // 
            // btnCollapseAll
            // 
            this.btnCollapseAll.Location = new System.Drawing.Point(81, 2);
            this.btnCollapseAll.Name = "btnCollapseAll";
            this.btnCollapseAll.Size = new System.Drawing.Size(75, 23);
            this.btnCollapseAll.TabIndex = 1;
            this.btnCollapseAll.Text = "Collapse";
            this.btnCollapseAll.UseVisualStyleBackColor = true;
            this.btnCollapseAll.Click += new System.EventHandler(this.BtnCollapseAll_Click);
            // 
            // btnExpandAll
            // 
            this.btnExpandAll.Location = new System.Drawing.Point(0, 2);
            this.btnExpandAll.Name = "btnExpandAll";
            this.btnExpandAll.Size = new System.Drawing.Size(75, 23);
            this.btnExpandAll.TabIndex = 0;
            this.btnExpandAll.Text = "Expand All";
            this.btnExpandAll.UseVisualStyleBackColor = true;
            this.btnExpandAll.Click += new System.EventHandler(this.BtnExpandAll_Click);
            // 
            // TXT_HeadLine
            // 
            this.TXT_HeadLine.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.TXT_HeadLine.BackColor = System.Drawing.Color.AliceBlue;
            this.TXT_HeadLine.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.TXT_HeadLine.Location = new System.Drawing.Point(0, 3);
            this.TXT_HeadLine.Name = "TXT_HeadLine";
            this.TXT_HeadLine.ReadOnly = true;
            this.TXT_HeadLine.Size = new System.Drawing.Size(486, 14);
            this.TXT_HeadLine.TabIndex = 8;
            this.TXT_HeadLine.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.TXT_HeadLine_MouseDoubleClick);
            // 
            // webBrowser1
            // 
            this.webBrowser1.AllowWebBrowserDrop = false;
            this.webBrowser1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.webBrowser1.IsWebBrowserContextMenuEnabled = false;
            this.webBrowser1.Location = new System.Drawing.Point(0, 21);
            this.webBrowser1.Margin = new System.Windows.Forms.Padding(0);
            this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
            this.webBrowser1.Name = "webBrowser1";
            this.webBrowser1.ScriptErrorsSuppressed = true;
            this.webBrowser1.Size = new System.Drawing.Size(489, 251);
            this.webBrowser1.TabIndex = 9;
            this.webBrowser1.WebBrowserShortcutsEnabled = false;
            // 
            // tvJSON
            // 
            this.tvJSON.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.tvJSON.BackColor = System.Drawing.Color.AliceBlue;
            this.tvJSON.Font = new System.Drawing.Font("Tahoma", 8.25F);
            this.tvJSON.Location = new System.Drawing.Point(0, 20);
            this.tvJSON.Name = "tvJSON";
            this.tvJSON.ShowNodeToolTips = true;
            this.tvJSON.Size = new System.Drawing.Size(489, 252);
            this.tvJSON.TabIndex = 0;
            this.tvJSON.Visible = false;
            // 
            // rtbox_Json
            // 
            this.rtbox_Json.AllowDrop = true;
            this.rtbox_Json.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.rtbox_Json.BackColor = System.Drawing.SystemColors.Control;
            this.rtbox_Json.Location = new System.Drawing.Point(0, 20);
            this.rtbox_Json.Margin = new System.Windows.Forms.Padding(0);
            this.rtbox_Json.Name = "rtbox_Json";
            this.rtbox_Json.Size = new System.Drawing.Size(489, 252);
            this.rtbox_Json.TabIndex = 11;
            // 
            // JSONView
            // 
            this.BackColor = System.Drawing.Color.AliceBlue;
            this.Controls.Add(this.tvJSON);
            this.Controls.Add(this.webBrowser1);
            this.Controls.Add(this.TXT_HeadLine);
            this.Controls.Add(this.rtbox_Json);
            this.Controls.Add(this.pnlFooter);
            this.Font = new System.Drawing.Font("Tahoma", 8.25F);
            this.Name = "JSONView";
            this.Size = new System.Drawing.Size(489, 297);
            this.Load += new System.EventHandler(this.JSONView_Load);
            this.pnlFooter.ResumeLayout(false);
            this.pnlFooter.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        private void Button1_Click(object sender, EventArgs e)
        {
            this.textShowBtn.Enabled = false;
            this.Btn_JSONZhuanYi.Enabled = this.rtbox_Json.GetReadOnly();
            this.webBrowser1.Visible = !isShowTextBox && isJson;
            this.tvJSON.Visible = false;
            this.rtbox_Json.Visible = !this.webBrowser1.Visible;
            rtbox_Json.SetText(CommonFunction.ConvertJsonString(this.Parent.Text == "RequestView" ? reqBody : resBody, false), false);
            //tbox_Json.Select();
        }

        private void JSONView_Load(object sender, EventArgs e)
        {

        }

        private void Btn_JSONZhuanYi_Click(object sender, EventArgs e)
        {
            string jsonStr = (this.Parent.Text == "RequestView" ? reqBody : resBody).Replace("\"", "\\" + "\"");
            this.rtbox_Json.SetText(jsonStr, false);
            this.rtbox_Json.Visible = true;
            this.webBrowser1.Visible = false;
            this.tvJSON.Visible = false;
            this.textShowBtn.Enabled = true;
            this.Btn_JSONZhuanYi.Enabled = false;
        }

        private void TXT_HeadLine_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Parent.Text == "RequestView")
            {
                TXT_HeadLine.SelectAll();
            }
        }

    }
}
